import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/models/file_list_entity.dart';
import 'package:seedfour/app/models/folder_list_entity.dart';

import '../../services/api_service.dart';
import '../../services/common_service.dart';

class FileListLogic extends GetxController {
  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();

  late FolderData folderData;
  late String title;

  final loadingTip = '加载中...';
  final noMoreTip = '没有更多了';

  var isLoading = true.obs;
  var bottomTips = ''.obs;
  var files = <FileData>[].obs;

  final scrollController = ScrollController();

  final pageSize = 20;
  int _page = 1;

  @override
  void onInit() {
    super.onInit();

    folderData = Get.arguments;
    title = '文件盘 / ${folderData.name}';

    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        _getFileList();
      }
    });

    _reload();
  }

  void _reload() {
    _page = 1;
    files.clear();
    _getFileList();
  }

  void _getFileList() {
    apiService
        .getFileList(_page, pageSize, commonService.getRole(),
            folderId: folderData.caseId!)
        .then((result) => {
              isLoading.value = false,
              _page++,
              if (result != null)
                {
                  files.addAll(result.data ?? []),
                  if (result.data!.length < pageSize)
                    {bottomTips.value = '${result.total} 个文件'}
                  else
                    {bottomTips.value = loadingTip}
                }
              else
                {bottomTips.value = noMoreTip}
            });
  }
}
